package com.bzframework.socket.configuration;

import com.bzframework.socket.mock.test.MockSocketHandler;
import com.bzframework.socket.mock.test.MockSocketHandlerInterceptor;
import com.bzframework.socket.sse.WebSocketMessagingHandler;
import com.bzframework.socket.sse.manager.DefaultMessagingManager;
import com.bzframework.socket.sse.manager.MessagingManager;
import com.bzframework.socket.sse.provider.SubscriptionProvider;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

@Configuration
@RequiredArgsConstructor
public class WebSocketMessagingHandlerConfiguration implements WebSocketConfigurer {

    private final MockSocketHandlerInterceptor mockSocketHandlerInterceptor;

    private final MockSocketHandler mockSocketHandler;

    private final ObjectProvider<SubscriptionProvider> providers;

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {

        registry.addHandler(mockSocketHandler, "/mock/**")
                .addInterceptors(mockSocketHandlerInterceptor)
                .setAllowedOrigins("*");

        registry.addHandler(webSocketMessagingHandler(defaultMessagingManager()), "/messaging/**")
                .setAllowedOrigins("*");

    }

    @Bean
    @ConditionalOnMissingBean(MessagingManager.class)
    public MessagingManager defaultMessagingManager() {
        DefaultMessagingManager messagingManager = new DefaultMessagingManager();
        providers.forEach(messagingManager::register);
        return messagingManager;
    }

    @Bean
    public WebSocketMessagingHandler webSocketMessagingHandler(MessagingManager messagingManager) {
        return new WebSocketMessagingHandler(messagingManager);
    }



}
